package spring.cloud.tasks.executor.listener.election;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.executor.utils.execute_callback.LeaderExecuteCallback;
import spring.cloud.tasks.executor.utils.log.LogUtils;

@Slf4j
@Setter
@Getter
class LeaderElectionLeaderExecuteCallback implements LeaderExecuteCallback {

    private final LeaderElectionService leaderElectionService;

    public LeaderElectionLeaderExecuteCallback(LeaderElectionService leaderElectionService) {
        this.leaderElectionService = leaderElectionService;
    }

    @Override
    public void execute() {
        synchronized (leaderElectionService.isShutdown) {
            if (leaderElectionService.isShutdown.get()) {
                return;
            }
            if (!leaderElectionService.getTaskNodeStorage().isTaskNodeExisted(ElectionNode.LEADER_HOST)) {
                leaderElectionService.getTaskNodeStorage().fillEphemeralTaskNode(ElectionNode.LEADER_HOST, leaderElectionService.executorId);
                LogUtils.info(log, leaderElectionService.taskId, "executor {} become job {}'s leader", leaderElectionService.executorId, leaderElectionService.taskId);
            }
        }
    }
}
